package servlet;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import dao.UserDao;
import bean.User;
public class ServletLogin extends HttpServlet {

    private static final long serialVersionUID = 1L;

    protected void service(HttpServletRequest request, HttpServletResponse response)
            throws IOException, ServletException {
        // 获取用户的账号密码
        String username = request.getParameter("name");
        String password = request.getParameter("password");

        // 创建user对象，将刚才获取的用户信息保存到对象
        User user = new User();
        user.setUsername(username);
        user.setPassword(password);
        user.setName("login");


        UserDao userDao = new UserDao();

        if(userDao.queryUser(user) ) {
            User user1 = userDao.queryPassword(user);
            if (user1!=null){

                // 设置对象属性
                request.getSession().setAttribute("user", user1);

                // 重定向
                response.sendRedirect("index");

            }

            else {
                response.setContentType("text/html; charset=UTF-8");
                response.getWriter().println("<script>alert('密码输入错误!'); window.location.href='login.jsp'</script>");
            }

        } else {
            response.setContentType("text/html; charset=UTF-8");
            response.getWriter().println("<script>alert('用户名不存在!'); window.location.href='login.jsp'</script>");
        }

    }
}